/*
* @Author: dengjiayao
* @Date:   2017-04-10 14:57:41
* @Last Modified by:   dengjiayao
* @Last Modified time: 2017-05-03 10:16:57
*/

import { modal } from 'vue-strap'
import extend from 'extend'
import { showMsg, addAIQuestion, updateAIQuestion } from '../../vuex/action'

export default {
  name: 'ai-question-config',
  components: {
    'vue-modal': modal
  },
  data() {
    return {
      showModal: false,
      actionType: 'CREATE', // CREATE, UPDATE
      form: {}
    }
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xAdd: addAIQuestion,
      xUpdate: updateAIQuestion
    }
  },
  methods: {
    check() {
      var fields = ['questionType', 'question', 'answerType']
      for (let i = 0, len = fields.length; i < len; i++) {
        let val = this.form[fields[i]] + ''
        if (!val.length) {
          return Promise.reject({
            error_msg: '* 标记的为必填项'
          })
        }
      }
      // 答案类别为问题时需要填写文字回答
      // 答案类别为其他时需要填写答案索引
      if (+this.form.answerType === 9) {
        if (this.form.answerContent.length === 0) {
          return Promise.reject({
            error_msg: '请填写文字回答'
          })
        }
      } else if (this.form.answerId.length === 0) {
        return Promise.reject({
          error_msg: '请填写答案索引'
        })
      }
      return Promise.resolve()
    },
    submit() {
      this.check()
        .then(() => {
          let params = extend({}, this.form)
          if (+params.answerType === 9) {
            delete params.answerId
          }
          if (this.actionType === 'CREATE') {
            return this.xAdd(params)
          } else {
            return this.xUpdate(params)
          }
        })
        .then(() => {
          this.showModal = false
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  }
}
